<template>
  <view class="search-input">
    <view class="input-box">
      <uni-icons type="search" size="16" color="#666"></uni-icons>
      <input
        type="text"
        v-model="inputValue"
        :placeholder="placeholder"
        confirm-type="search"
        @confirm="onConfirm"
        @input="onInput"
        @focus="onFocus"
      />
      <uni-icons
        v-if="inputValue"
        type="clear"
        size="16"
        color="#999"
        @click="clearInput"
      ></uni-icons>
    </view>
    <button class="search-btn" @tap="onConfirm">搜索</button>
    <text v-if="showCancel" class="cancel-btn" @tap="onCancel">取消</text>
  </view>
</template>

<script>
export default {
  name: 'SearchInput',
  emits: ['update:modelValue', 'confirm', 'focus', 'clear', 'cancel'],
  props: {
    modelValue: {
      type: String,
      default: ''
    },
    placeholder: {
      type: String,
      default: '搜索商品'
    },
    showCancel: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      inputValue: this.modelValue
    }
  },
  watch: {
    modelValue(newVal) {
      this.inputValue = newVal
    }
  },
  methods: {
    onInput() {
      this.$emit('update:modelValue', this.inputValue)
    },
    onConfirm() {
      const trimmedValue = this.inputValue.trim()
      if (!trimmedValue) {
        uni.showToast({
          title: '请输入搜索关键词',
          icon: 'none'
        })
        return
      }
      this.$emit('confirm', trimmedValue)
    },
    onFocus() {
      this.$emit('focus')
    },
    clearInput() {
      this.inputValue = ''
      this.$emit('update:modelValue', '')
      this.$emit('clear')
    },
    onCancel() {
      this.clearInput()
      this.$emit('cancel')
    }
  }
}
</script>

<style lang="scss" scoped>
.search-input {
  display: flex;
  align-items: center;
  padding: 16rpx;
  background-color: #fff;

  .input-box {
    flex: 1;
    display: flex;
    align-items: center;
    height: 64rpx;
    background-color: #f5f5f5;
    border-radius: 32rpx;
    padding: 0 24rpx;

    .uni-icons {
      margin-right: 12rpx;
    }

    input {
      flex: 1;
      height: 100%;
      font-size: 28rpx;
    }
  }

  .search-btn {
    margin: 0 16rpx;
    padding: 0 32rpx;
    height: 64rpx;
    line-height: 64rpx;
    font-size: 28rpx;
    color: #fff;
    background: linear-gradient(to right, #ff7300, #ff5500);
    border-radius: 32rpx;
    border: none;
  }

  .cancel-btn {
    padding: 0 20rpx;
    font-size: 28rpx;
    color: #666;
  }
}
</style> 